package com.tbvtc.agriculturalcreditchainserver2025.config;

import com.fasterxml.jackson.core.type.TypeReference;
import com.tbvtc.agriculturalcreditchainserver2025.dto.Cart.Item;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

@MappedTypes(List.class) // 声明处理的 Java 类型
public class JsonToListTypeHandler extends BaseTypeHandler<List<Item>> {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Item> parameter, JdbcType jdbcType) throws SQLException {
        // 写入数据库时不需要处理（根据需求可选实现）
    }

    @Override
    public List<Item> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseJson(rs.getString(columnName));
    }

    @Override
    public List<Item> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseJson(rs.getString(columnIndex));
    }

    @Override
    public List<Item> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseJson(cs.getString(columnIndex));
    }

    private List<Item> parseJson(String json) {
        try {
            return objectMapper.readValue(json, new TypeReference<List<Item>>() {});
        } catch (Exception e) {
            return Collections.emptyList();
        }
    }
}